import {commomParams,ERR_OK} from "../api/config"
import {getUid} from "../commom/js/uid"
import axios from 'axios'

export function getplaysongkey(mid){
  const url = '/getplaysongkey';
  // let url = 'https://u.y.qq.com/cgi-bin/musics.fcg';
  let data = {
    '-': 'getplaysongvkey9116411966766595',
    loginUin: '240046220',
    g_tk:'1870062489',
    sign:'zzae8j78ylg5mrr2hur9a15ee71195f2ad8052d7ae3f0f2279f',
    data: `{"req":{"module":"CDN.SrfCdnDispatchServer","method":"GetCdnDispatch","param":{"guid":"7213711195","calltype":0,"userip":""}},"req_0":{"module":"vkey.GetVkeyServer","method":"CgiGetVkey","param":{"guid":"7213711195","songmid":["${mid}"],"songtype":[0],"uin":"1152921504863479195","loginflag":1,"platform":"20"}},"comm":{"uin":"1152921504863479195","format":"json","ct":24,"cv":0}}`
  }
  const urldata = Object.assign({},commomParams,data);
  return axios.get(url,{params:urldata}).then((res)=>{
    return Promise.resolve(res.data.req_0.data ? res.data.req_0.data.midurlinfo[0].purl : undefined);
  })
}

export function getLyric(mid = '001kGz0W0RLoXD'){//获取歌词
  const url = "/api/getSongLyric";
  let data = {
    '-': 'MusicJsonCallback_lrc',
    pcachetime: 1616315112419,
    songmid: mid,
    g_tk_new_20200303: 5381,
    loginUin: 0
  }
  const urldata = Object.assign({},commomParams,data);
  return axios.get(url,{params:urldata}).then((res)=>{
    return Promise.resolve(res.data)
  })
}

export function getSongsUrl(songs){
  const url = '/api/getPurlUrl'
  let mids = []
  let types = []
  songs.forEach((item)=>{
    mids.push(item.mid);
    types.push(0)
  })
  const urlMid = geturlMid(mids, types)
  const data = Object.assign({}, commomParams, {
    g_tk: 5381,
    format: 'json',
    platform: 'h5',
    needNewCode: 1,
    uin: 0
  })
  return new Promise((resolve, reject) => {
    let tryTime = 3

    function request() {
      return axios.post(url, {
        comm: data,
        url_mid: urlMid
      }).then((response) => {
        const res = response.data
        if (res.code === ERR_OK) {
          let urlMid = res.url_mid
          if (urlMid && urlMid.code === ERR_OK) {
            const info = urlMid.data.midurlinfo[0]
            if (info && info.purl) {
              resolve(res)
            } else {
              retry()
            }
          } else {
            retry()
          }
        } else {
          retry()
        }
      })
    }

    function retry() {
      if (--tryTime >= 0) {
        request()
      } else {
        reject(new Error('Can not get the songs url'))
      }
    }

    request()
  })
}


function geturlMid(mids,types){
  const guid = getUid();
  return {
    module: 'vkey.GetVkeyServer',
    method: "CgiGetVkey",
    param: {
      guid,
      songmid: mids,
      songtype: types,
      uin: '0',
      loginflag: 0,
      platform: '23'
    }
  }
}